<template>
  <div class="container" ref="mainCon">
    <el-row
      class="toolbar searchInputWidth"
      style="padding-bottom: 0; padding-top: 24px !important"
    >
      <el-form :inline="true" :model="filterField" ref="searchConditions">
        <el-col :lg="8" :xl="6">
          <el-form-item label="项目名称" class="row-padding-bottom">
            <el-input
              v-model="filterField.projectName"
              placeholder="请输入项目名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="8" :xl="6">
          <el-form-item label="区域" class="row-padding-bottom">
            <el-cascader
              ref="manageArea"
              v-model="areaId"
              :options="areasOptions"
              @change="getAreaId"
              clearable
              filterable
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <template v-if="advanced">
          <el-col :lg="8" :xl="6">
            <el-form-item label="行业" class="row-padding-bottom">
              <el-select
                v-model="filterField.industryId"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="建设方" class="row-padding-bottom">
              <el-input
                v-model="filterField.pcName"
                placeholder="请输入建设方名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="施工方" class="row-padding-bottom">
              <el-input
                v-model="filterField.pbName"
                placeholder="请输入施工方名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="投资类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.investment"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in investmentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="开设专户" class="row-padding-bottom">
              <el-select
                v-model="filterField.isSa"
                placeholder="请选择"
                clearable
              >
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="项目来源" class="row-padding-bottom">
              <el-select
                v-model="filterField.sourceType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in sourceTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item
              label="包保人"
              class="row-padding-bottom"
              v-if="activeName == 1"
            >
              <el-input
                v-model="filterField.guards"
                placeholder="请输入包保人"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </template>
        <el-col :lg="8" :xl="6">
          <el-form-item>
            <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button> -->
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div class="spacing"></div>
    <div
      ref="tableBox"
      :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
    >
      <el-table
        ref="tableBox1"
        :data="tableList"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        style="border: 1px solid #dfe6ec"
        :max-height="tableHeight"
      >
        <el-table-column prop="projectName" label="项目名称" width="230px">
          <template slot-scope="scope">
            <!-- <el-link
                            type="primary"
                            @click="toDetail(scope.$index, scope.row)"
                            >{{scope.row.projectName}}</el-link> -->
            <div @click="toDetail(scope.$index, scope.row)" class="fontColor">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.projectName"
                :columnName="'projectName'"
              ></copyText>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="areaName"
          label="区域"
          align="center"
          :formatter="formatTd"
          min-width="210"
        ></el-table-column>
        <el-table-column
          prop="industryName"
          label="行业"
          align="center"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          prop="pcName"
          label="建设方"
          :formatter="formatTd"
          width="230px"
        >
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.pcName"
              :columnName="'pcName'"
            ></copyText>
          </template>
        </el-table-column>
        <el-table-column
          prop="pbName"
          label="施工方"
          :formatter="formatTd"
          width="230px"
        >
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.pbName"
              :columnName="'pbName'"
            ></copyText>
          </template>
        </el-table-column>
        <el-table-column
          prop="investmentDesc"
          label="投资类型"
          align="center"
          :formatter="formatTd"
          width="180px"
        ></el-table-column>
        <el-table-column
          prop="isSaDesc"
          label="是否开设专户"
          align="center"
          :formatter="formatTd"
          width="120px"
        ></el-table-column>
        <el-table-column
          prop="sourceTypeText"
          label="项目来源"
          align="center"
          :formatter="formatTd"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="guards"
          label="包保责任人"
          align="center"
          :formatter="formatTd"
          v-if="activeName == 1"
          width="230"
        >
          <template slot-scope="scope">
            <copyText
              :tableIndex="scope.$index"
              :copyTextName="scope.row.guards"
              :columnName="'guards'"
            ></copyText>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" fixed="right" width="230px">
          <template slot-scope="scope">
            <el-link
              type="primary"
              v-hasBtn="'mGuaranteedDistribution:update'"
              @click="addPersonLiable(scope.$index, scope.row, 'edit')"
              v-if="activeName == 1"
              >修改责任人</el-link
            >
            <el-link
              type="primary"
              v-hasBtn="'mGuaranteedDistribution:delete'"
              @click="delGuaranteed(scope.$index, scope.row)"
              v-if="activeName == 1"
              >移除包保</el-link
            >
            <el-link
              type="primary"
              v-hasBtn="'mGuaranteedDistribution:add'"
              @click="addPersonLiable(scope.$index, scope.row, 'add')"
              v-if="activeName == 0"
              >分派责任人</el-link
            >
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <Pagination
        ref="pagination"
        @getpageNo="getpageNo"
        @getpageSize="getpageSize"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
    </div>
    <el-dialog
      :title="isUpdate == 'edit' ? '修改包保负责人' : '分派包保负责人'"
      :visible.sync="dialogVisible"
      width="640px"
      @close="handleClose"
      :modal-append-to-body="false"
    >
      <el-form
        class="el-form1 mrT8"
        :model="formData"
        ref="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="监察员：" prop="guardLeaders">
          <el-select
            clearable
            filterable
            multiple
            placeholder="请选择"
            v-model="guardLeaders"
            :popper-append-to-body="false"
            class="selectInspectorSty dialogSingleInp"
          >
            <el-option
              v-for="item in jcInspectorOptions"
              :key="item.id"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            >
              <p>{{ item.nickname + '(' + item.username + ')' }}</p>
              <p
                style="color: #8492a6; font-size: 12px; margin-top: 2px"
                v-if="radio != '2'"
              >
                {{ item.areaName }}
              </p>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他包保人：" class="radioSty" prop="radio">
          <el-radio-group v-model="radio">
            <el-radio :label="1" :disabled="isDisabledHY">行业主管</el-radio>
            <el-radio :label="2" :disabled="isDisabledJS"
              >建设业主（政府项目业主负责）</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" class="radioSty" prop="guardMembers">
          <el-select
            clearable
            filterable
            multiple
            placeholder="请选择"
            v-model="guardMembers"
            :popper-append-to-body="false"
            class="selectInspectorSty dialogSingleInp"
          >
            <el-option
              v-for="item in inspectorOptions"
              :key="item.id"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            >
              <p>{{ item.nickname + '(' + item.username + ')' }}</p>
              <p
                style="color: #8492a6; font-size: 12px; margin-top: 2px"
                v-if="radio != '2'"
              >
                {{ item.areaName }}
              </p>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" class="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="onSave"
          :loading="isSaveLoading"
          class="save"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'proAssigned',
  props: ['activeName'],
  data() {
    return {
      tableList: [],
      requestUrl: 'api-p/projectguard/expand/find',
      areaId: '', //区域
      //搜索条件
      filterField: {
        projectName: '', //项目名称
        areaId: '', //区域
        status: '', //开工状态  ；默认只显示已开工状态的项目2020/10/19 恩施
        industryId: '', //行业
        investment: '', //投资类型
        isSa: '', //是否开设专户
        pcName: '', //建设方
        pbName: '', //施工方
        sourceType: '', //项目来源
        serverArea: '', // 服务部署区域
        guards: '', //包保人
        isGuard: 0,
      },
      pageSize: 20,
      pageNo: 1,
      isShow: false, //列表加载
      isShowDetail: '',
      isShowUpdate: '',
      loading: true,
      sourceTypeOptions: [], //项目来源
      multipleSelection: [], //当前选中项
      projectIdArr: [],
      formData: {
        guardLeaders: '',
        guardMembers: '',
        projectId: '',
        radio: 1,
      },
      guardLeaders: [],
      guardMembers: [],
      radio: 1,
      rules: {
        guardLeaders: [
          {
            required: true,
            message: '请选择监察员',
            trigger: 'blur',
          },
        ],
        // guardMembers:[
        //     {
        //         required: true,
        //         message: "请选择",
        //         trigger:"blur"
        //     }
        // ],
        // radio:[
        //     {
        //         required: true,
        //         message: " ",
        //         trigger:"blur"
        //     }
        // ],
      },
      isSaveLoading: false,
      userType: '',
      dialogVisible: false,
      inspectorOptions: [], //行业主管、建设业主包保人
      jcInspectorOptions: [], //监察包保人
      isUpdate: '',
      isDisabledHY: false,
      isDisabledJS: false,
      projectId: '',
      advanced: false,
      tableHeight: null,
      hiddleToolBar: false,
    }
  },
  computed: {
    ...mapState([
      'investmentOptions',
      'statusOptions',
      'areasOptions',
      'industryOptions',
    ]),
  },
  watch: {
    activeName(val, oldVal) {
      this.filterField.projectName = ''
      this.filterField.areaId = ''
      this.filterField.status = ''
      this.filterField.industryId = ''
      this.filterField.isSa = ''
      this.filterField.pcName = ''
      this.filterField.pbName = ''
      this.filterField.sourceType = ''
      this.areaId = ''
      this.filterField.guards = ''
      this.filterField.isGuard = val
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    },
  },
  created() {
    this.userType = this.$store.state.userType
    this.getInvestmenttype({})
    this.getStatus({})
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getIndustry({})
    this.getSourceType()
    this.filterField.serverArea = this.$store.state.areaInfoArr.areaId
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    ...mapActions([
      'getInvestmenttype',
      'getStatus',
      'getAreas',
      'getIndustry',
    ]),
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.pageSize = 20
      this.pageNo = 1
      this.$refs.pagination.getTableListData()
    },
    // 项目名称跳转详情
    toDetail(index, row) {
      this.$router.push({
        path: '/home/monitorProjectManagement/projectDetail',
        name: 'projectDetail',
        query: {
          projectId: row.projectId,
          mark: 'assigned',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/project/projectList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getSourceType() {
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/sourceType',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.sourceTypeOptions = response.data.result
          }
        })
        .catch({})
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs.formData.resetFields()
    },
    // 分派负责人和修改
    addPersonLiable(index, row, type) {
      this.isUpdate = type
      this.projectId = row.projectId
      ;(this.guardLeaders = []),
        (this.guardMembers = []),
        (this.inspectorOptions = [])
      this.radio = 1
      this.formData = {
        guardLeaders: '',
        guardMembers: '',
        radio: 1,
      }
      this.getIsGov(row)
      this.getGuards(row.projectId, 'MONITOR', '')
      if (this.radio == '1') {
        this.getGuards(row.projectId, 'DIRECTOR', row.industryId)
      } else {
        this.getGuards(row.projectId, 'PROJECT_OWNER', '')
      }
      if (type == 'edit') {
        this.getEditDetail(row)
      }
    },
    // 移除包保
    delGuaranteed(index, row) {
      this.$confirm('确认删除该项目的包保负责人吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.toDel(row.projectId)
        })
        .catch(() => {})
    },
    toDel(projectId) {
      this.axios({
        method: 'post',
        url: 'api-p/projectguard/expand/delguard',
        data: { projectId: projectId },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            //删除成功刷新列表
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('删除失败')
        })
    },
    // 分派负责人保存
    onSave() {
      this.isSaveLoading = true
      if (this.guardLeaders) {
        this.formData.guardLeaders = this.guardLeaders.join(',')
      }
      if (this.guardMembers) {
        this.formData.guardMembers = this.guardMembers.join(',')
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.toSuccess()
        } else {
          this.isSaveLoading = false
        }
      })
    },
    toSuccess() {
      let url
      if (this.isUpdate == 'add') {
        url = 'api-p/projectguard/expand/add'
      } else {
        url = 'api-p/projectguard/expand/modify'
      }
      this.axios({
        method: 'post',
        url: url,
        data: {
          guardLeaders: this.formData.guardLeaders,
          guardMembers: this.formData.guardMembers,
          projectId: this.projectId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.dialogVisible = false
              this.$refs.formData.resetFields()
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
            this.isSaveLoading = false
          },
          (response) => {
            this.isSaveLoading = false
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    // 获取添加中的包保人
    getGuards(projectId, userType, industryId) {
      var urlData
      if (userType == 'DIRECTOR') {
        urlData = {
          projectId: projectId,
          userType: userType,
          industryId: industryId,
        }
      } else {
        urlData = {
          projectId: projectId,
          userType: userType,
        }
      }

      return this.axios({
        method: 'post',
        url: 'api-u/users/findbytypeandarea',
        data: urlData,
      })
        .then((response) => {
          if (!response.data.hasError) {
            if (userType == 'MONITOR') {
              this.jcInspectorOptions = response.data.result
            } else {
              this.inspectorOptions = response.data.result
            }
            this.dialogVisible = true
          }
        })
        .catch({})
    },
    // 获取修改详情
    getEditDetail(row) {
      this.axios({
        method: 'post',
        url: 'api-p/projectguard/expand/detail',
        data: { projectId: row.projectId },
      })
        .then((response) => {
          if (!response.data.hasError) {
            var data = response.data.result[0]
            if (data.guardLeaders) {
              this.formData.guardLeaders = data.guardLeaders.split(',')
              this.guardLeaders = data.guardLeaders.split(',')
            } else {
              this.formData.guardLeaders = data.guardLeaders
              this.guardLeaders = data.guardLeaders
            }
            if (data.guardMembers) {
              this.formData.guardMembers = data.guardMembers.split(',')
              this.guardMembers = data.guardMembers.split(',')
            } else {
              this.formData.guardMembers = data.guardMembers
              this.guardMembers = data.guardMembers
            }
            this.getIsGov(row)
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('获取数据失败')
        })
    },
    getIsGov(row) {
      if (row.investment == 'GOV') {
        this.isDisabledHY = true
        this.isDisabledJS = false
        this.radio = 2
        this.formData.radio = 2
      } else {
        this.isDisabledHY = false
        this.isDisabledJS = true
        this.radio = 1
        this.formData.radio = 1
      }
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 218

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.container {
  // padding:24px;
}
.selectInspectorSty /deep/ .el-select-dropdown__item {
  padding: 5px 20px !important;
  height: initial !important;
  line-height: initial !important;
}
.selectInspectorSty
  /deep/
  .el-select-dropdown.is-multiple
  .el-select-dropdown__item.selected::after {
  top: 7px;
}
.radioSty /deep/ .el-form-item__content {
  // margin-left:80px  !important;
}
.radioSty {
  margin-bottom: 8px !important;
}
.optionWidth {
  width: 310px !important;
}
@media only screen and (max-width: 1366px) {
  /deep/.searchInputWidth .el-form--inline .el-form-item__label {
    width: 80px;
  }
}
@import '../../../static/css/filterArea.less';
.fontColor {
  color: #409eff;
  cursor: pointer;
}
</style>
